package com.hy.service.impl;

import com.baomidou.mybatisplus.core.conditions.AbstractWrapper;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hy.domain.BlogFollow;
import com.hy.domain.dto.UserDTO;
import com.hy.service.BlogFollowService;
import com.hy.mapper.BlogFollowMapper;
import com.hy.util.UserHolder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
* @author hou
* @description 针对表【blog_follow】的数据库操作Service实现
* @createDate 2023-05-01 12:31:36
*/
@Service
public class BlogFollowServiceImpl extends ServiceImpl<BlogFollowMapper, BlogFollow>
    implements BlogFollowService{

    @Override
    public boolean isFollow(Long id) {
        final Long userId = UserHolder.getUser().getUserId();
        final Integer count = lambdaQuery().eq(BlogFollow::getUserId, userId).eq(BlogFollow::getFollowId, id).count();
        return count > 0;
    }

    @Override
    public boolean follow(Long id, Boolean isFollow) {
        final UserDTO user = UserHolder.getUser();
        // 关注
        if (isFollow) {
            final BlogFollow blogFollow = new BlogFollow();
            blogFollow.setUserId(user.getUserId());
            blogFollow.setFollowId(id);
            blogFollow.setCreateTime(LocalDateTime.now());
            System.out.println("blogFollow = " + blogFollow);
            final boolean save = save(blogFollow);
            return save;
        } else {
            // 取关
            final AbstractWrapper<BlogFollow, SFunction<BlogFollow, ?>, LambdaQueryWrapper<BlogFollow>> wrapper = lambdaQuery()
                    .eq(BlogFollow::getUserId, user.getUserId())
                    .eq(BlogFollow::getFollowId, id)
                    .getWrapper();
            final boolean remove = remove(wrapper);
            return !remove;
        }
    }
}




